﻿using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YUN.ProductionManage.IRepositories;

namespace YUN.ProductionManage.Services
{
    public partial class Product_ProductOrderService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IProduct_ProductOrderRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]
        public Product_ProductOrderService(
            IProduct_ProductOrderRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBase_NumberRuleRepository numberRuleRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _numberRuleRepository = numberRuleRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            var productcode = 1;//生产编号
            var ordercode = 1;//订单编号
            //保存数据库前处理
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (ProductionOrderInfo productorder, object list) =>
            {
                if (string.IsNullOrWhiteSpace(productorder.ProductionOrderCode))
                {
                    productorder.ProductionOrderCode = GetProductionCode();
                }
                if (string.IsNullOrWhiteSpace(productorder.OrderCode))
                {
                    productorder.OrderCode = GetProductionOrderCode();
                }
                //如果返回false,后面代码不会再执行、
                if (repository.Exists(x => x.ProductionOrderCode == productorder.ProductionOrderCode))
                {
                    return webResponse.Error("生产编号已存在");
                }
                if (repository.Exists(x => x.OrderCode == productorder.OrderCode))
                {
                    return webResponse.Error("订单编号已存在");
                }

                return webResponse.OK();
            };
            //扩展字段开始 start
            AddOnExecuted = (ProductionOrderInfo product, object list) =>
            {
                return webResponse.OK();
            };
            try
            {
                // 你的数据库更新代码
                //扩展字段开始 end
                return base.Add(saveDataModel);
            }
            catch (Exception ex)
            {
                // 记录或显示完整的异常信息，包括 inner exception
                Console.WriteLine(ex.ToString());
                // 或者在前端显示
                throw new Exception($"Error: {ex.Message}. Inner Exception: {ex.InnerException?.Message}");
            }
        }
        public override PageGridData<ProductionOrderInfo> GetPageData(PageDataOptions options)
        {
            return base.GetPageData(options);
        }
        /// <summary>
        /// 自动生成我的生产编号
        /// </summary>
        /// <returns></returns>
        public string GetProductionCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.ProductionOrderCode.Length > 8)
                .OrderByDescending(x => x.ProductionOrderCode)
                .Select(s => s.ProductionOrderCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "MyProduct")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
        /// <summary>
        /// 自动生成我的生产订单编号
        /// </summary>
        /// <returns></returns>
        public string GetProductionOrderCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            //x.CreateDate > dateNow &&
            string defectItemCode = repository.FindAsIQueryable(x =>  x.OrderCode.Length > 8)
                .OrderByDescending(x => x.OrderCode)
                .Select(s => s.OrderCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "MyProductOrder")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
        public async Task<WebResponseContent> ExportProductionOrdersAsync()
        {
            try
            {
                // 查询需要导出的数据
                var productionOrders = await _repository.FindAsync(x => true); // 查询所有生产订单

                if (productionOrders == null || !productionOrders.Any())
                {
                    return webResponse.Error("没有可导出的数据");
                }

                // 创建 Excel 文件
                using (var package = new ExcelPackage())
                {
                    var worksheet = package.Workbook.Worksheets.Add("生产订单信息");
                    // 添加表头
                    worksheet.Cells[1, 1].Value = "生产订单编号";
                    worksheet.Cells[1, 2].Value = "订单编号";
                    worksheet.Cells[1, 3].Value = "客户ID";
                    worksheet.Cells[1, 4].Value = "生产状态";
                    worksheet.Cells[1, 5].Value = "创建时间";

                    // 填充数据
                    for (int i = 0; i < productionOrders.Count; i++)
                    {
                        var order = productionOrders[i];
                        worksheet.Cells[i + 2, 1].Value = order.ProductionOrderCode;
                        worksheet.Cells[i + 2, 2].Value = order.OrderCode;
                        worksheet.Cells[i + 2, 3].Value = order.DCustomerId;
                        worksheet.Cells[i + 2, 4].Value = order.ProductStatus;
                        worksheet.Cells[i + 2, 5].Value = order.CreateDate?.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    // 自动调整列宽
                    worksheet.Cells.AutoFitColumns();

                    // 将 Excel 文件保存到内存流
                    var stream = new MemoryStream();
                    package.SaveAs(stream);
                    stream.Position = 0;

                    // 将文件转换为 Base64 字符串返回
                    var base64File = Convert.ToBase64String(stream.ToArray());
                    return webResponse.OK("导出成功", new { FileName = "生产订单.xlsx", FileContent = base64File });
                }
            }
            catch (Exception ex)
            {
                return webResponse.Error($"导出失败: {ex.Message}");
            }
        }
    }
}
